package com.heima.search.service.impl;

import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApArticleSearch;
import com.heima.search.entity.ApUserSearch;
import com.heima.search.repository.ArticleRepository;
import com.heima.search.service.IArticleSearchService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author Mr_Su
 * @version v1.0
 * @date 2022/7/10 20:17
 * @desciption
 */
@Service
public class ArticleSearchServiceImpl implements IArticleSearchService {

    @Autowired
    private ArticleRepository articleRepository;

    @Autowired
    private ApUserSearchServiceImpl apUserSearchService;
    @Override
    public ResponseResult search(ApArticleSearchDto dto) {

        if (StringUtils.isBlank(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 根据标题模糊查询
        QueryBuilder query = QueryBuilders.matchQuery("title",dto.getSearchWords());
        // 按照发布时间倒序排序
        // 分页查询
        Pageable pageable = PageRequest.of(dto.getPage().intValue() - 1,dto.getSize(), Sort.by(Sort.Direction.DESC,"publishTime"));
        Page<ApArticleSearch> searchPage = articleRepository.search(query, pageable);

        // 保存用户的搜索记录(采用异步的方式)
        apUserSearchService.saveUserSearch(dto.getSearchWords(), UserThreadLocalUtil.get().getUserId(), dto.getEquipmentId());



        return ResponseResult.okResult(searchPage.getContent());
    }

}
